package task

import (
	"time"

	"gitee.com/sansaniot/ssiot-core/facade/env"

	"ssadmin/common/constant"
	dto "ssadmin/common/query"
	"ssadmin/internal/admin/models"
)

// DevStatTask 设备数、设备活跃数统计
func DevStatTask() {
	devModel := &models.SysDev{}
	devModel.Orm = env.Db
	devList := make([]models.SysDev, 0)
	_ = devModel.FindList(&devList)
	if len(devList) == 0 {
		return
	}
	// 按分组的设备数
	deptDevCnt := make(map[string]int)
	// 按分组的活跃设备数
	deptDevActiveCnt := make(map[string]int)
	for _, dev := range devList {
		if len(dev.DeptId) == 0 {
			continue
		}
		deptDevCnt[dev.DeptId]++
		if dev.OnlineStatus == "online" {
			deptDevActiveCnt[dev.DeptId]++
		}
	}
	sysDataDetailModel := &models.SysDataDetail{}
	sysDataDetailModel.Orm = env.Db
	for deptId, cnt := range deptDevCnt {
		if err := sysDataDetailModel.Add(&models.SysDataDetail{
			Type:       constant.TypeOfDevCount,
			Key:        deptId,
			Value:      cnt,
			CreateTime: dto.LocalTime(time.Now()),
		}); err != nil {
			env.Log.Error(err)
		}
	}
	for deptId, cnt := range deptDevActiveCnt {
		if err := sysDataDetailModel.Add(&models.SysDataDetail{
			Type:       constant.TypeOfDevActiveCount,
			Key:        deptId,
			Value:      cnt,
			CreateTime: dto.LocalTime(time.Now()),
		}); err != nil {
			env.Log.Error(err)
		}
	}

}
